//
//  MainAllListView.swift
//  MakeMoney
//
//  Created by Fan ZhiQiang on 2025/3/26.
//

import SwiftUI

struct MainAllListView: View {
    @State private var task: Task<Void, Never>?
    //@State private var task1: Task<Void, Never>?
    @Bindable var pathStore: PathStore
    var body: some View {
        LotterysView(lotterys: total)
            .toolbar(.hidden, for: .tabBar)
            .navigationTitle("列表")
            .navigationBarTitleDisplayMode(.inline)
            .onAppear {
                task = Task {
                    Task {
                        print("onAppear 执行 init Task")
                        await testInitTask()
                        print("init Task over")
                    }
                }
                Task {
                    Task.detached {
                        print("onAppear 执行 分离 Task")
                        await testDetatchedTask()
                        print("分离 Task over")
                    }
                }
            }
            .onDisappear {
                //task1?.cancel()
                task?.cancel()
            }
    }
    
    func testInitTask() async {
        print("testInitTask")
        // 检查是否已被取消，若已取消则直接返回
        guard !Task.isCancelled else {
            print("init Task 已被取消，提前退出")
            return
        }
        
        // 尝试睡眠，若被取消会抛出错误
        do {
            try await Task.sleep(for: .seconds(4))
        } catch is CancellationError {
            // 捕获取消错误，提前退出
            print("init Task 在睡眠中被取消")
            return
        } catch {
            // 处理其他错误
        }
        
        // 只有未被取消且睡眠完成，才会打印
        print("init Task over")
    }
    
    func testDetatchedTask() async {
        print("testDetatchedTask")
        try? await Task.sleep(for: .seconds(6))
    }
}

#Preview {
    MainAllListView(pathStore: .init())
}

class MainAllListPath: PathName { }
